﻿using MiniFox.Components;
using MiniFox.Data.EntityFramework;
using MiniFox.Platform;
using MiniFox.Platform.Applications.Models;
using MiniFox.Platform.Applications.Providers;

namespace Platform.Data
{
    /// <summary>
    /// 
    /// </summary>
    [AutoResolve]
    public class RoleProvider : EntityDataProvider<PlatformDbContext>, IRoleProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        public IEnumerable<SystemRole> GetModuleRoles(SystemNavModuleEntry module)
        {
            var roles = (from r in this.CurrentDbContext.SysRole
                         join rm in this.CurrentDbContext.SysRoleModule on r.RoleId equals rm.RoleId
                         where rm.ModuleId == module.ID
                         select new SystemRole
                         {
                             RoleID = r.RoleId,
                             Name = r.RoleName,
                             DisplayName = r.RoleName
                         }).ToArray();
            return roles;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public IEnumerable<SystemRole> GetModuleRoles(SystemNavModuleAction action)
        {
            var roles = (from r in this.CurrentDbContext.SysRole
                         join rm in this.CurrentDbContext.SysRoleModule on r.RoleId equals rm.RoleId
                         join rma in this.CurrentDbContext.SysRoleModuleAction on new { rm.RoleId, rm.ModuleId } equals new { rma.RoleId, rma.ModuleId }
                         where rma.ActionId == action.ID
                         select new SystemRole
                         {
                             RoleID = r.RoleId,
                             Name = r.RoleName,
                             DisplayName = r.RoleName
                         }).ToArray();
            return roles;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public IEnumerable<SystemRole> GetUserRoles(SystemIdentity identity)
        {
            var roles = (from r in this.CurrentDbContext.SysRole
                         join ur in this.CurrentDbContext.SysUserRole on r.RoleId equals ur.RoleId
                         where ur.UserId == identity.GlobalID
                         select new SystemRole
                         {
                             RoleID = r.RoleId,
                             Name = r.RoleName,
                             DisplayName = r.RoleName
                         }).ToArray();
            return roles;
        }
    }
}
